package com.ithero.contentcenter;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.ithero.contentcenter.dao.content.ShareMapper;
import com.ithero.contentcenter.domain.entity.content.Share;
import com.ithero.contentcenter.feignclient.TestBaiduFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RefreshScope   // 开启配置动态刷新
public class TestController {

    @Autowired
    private ShareMapper shareMapper;

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/test")
    public Share testInsert() {
        Share share = new Share();
        share.setCreateTime(new Date());
        share.setUpdateTime(new Date());

        shareMapper.insertSelective(share);
        return share;
    }

    @GetMapping("/test2")
    public List<ServiceInstance> test2() {
        return this.discoveryClient.getInstances("user-center");
    }

    @Autowired
    private TestBaiduFeignClient testBaiduFeignClient;

    @GetMapping("baidu")
    public String baiduIndex() {
        return this.testBaiduFeignClient.index();
    }

    @Autowired
    private TestService testService;

    @GetMapping("testA")
    public String testA() {
        testService.common();
        return "testA";
    }

    @GetMapping("testB")
    public String testB() {
        testService.common();
        return "testB";
    }

    /**
     * 测试代码配置流控规则
     */
    @GetMapping("test-add-flow-rule")
    public String testFlowQpsRule() {
        initFlowQpsRule();
        return "SUCCESS";
    }

    private void initFlowQpsRule() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule flowRule = new FlowRule("/shares/1");
        flowRule.setCount(20);
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule.setLimitApp("default");
        rules.add(flowRule);
        FlowRuleManager.loadRules(rules);
    }


    /**
     * 测试SentinelAPI
     */
    @GetMapping("/test-sentinel-api")
    public String testSentinelAPI(@RequestParam(required = false) String a) {
        String resourceName = "test-sentinel-api";

        ContextUtil.enter(resourceName, "test-wfw");

        // 定义一个sentinel保护的资源，名称是test-sentinel-api
        Entry entry = null;
        try {
            entry = SphU.entry(resourceName);
            if (StringUtils.isEmpty(a)) {
                throw new IllegalArgumentException("a不能为空！");
            }
            return a;
        } catch (BlockException e) {
            log.error("限流或者降级了", e);
            return "限流或者降级了";
        } catch (IllegalArgumentException e2) {
            // 统计IllegalArgumentException
            Tracer.trace(e2);
            return "非法参数！";
        } finally {
            if (entry != null) {
                // 退出entry
                entry.exit();
            }
            ContextUtil.exit();
        }
    }

    @GetMapping("/test-sentinel-resource")
    @SentinelResource(value = "test-sentinel-resource", blockHandler = "block", fallback = "fallback")
    public String testSentinelResource(@RequestParam(required = false) String a) {
        if (StringUtils.isEmpty(a)) {
            throw new IllegalArgumentException("a can not be blank");
        }
        return a;
    }

    /**
     * 处理流控或者降级
     */
    public String block(String a, BlockException e) {
        log.error("限流或者降级了", e);
        return "限流或者降级了";
    }

    /**
     * 处理降级
     */
    public String fallback(String a) {
        log.error("降级了");
        return "降级了";
    }

    @Autowired
    private Source source;

    @GetMapping("/test-stream")
    public String testStream() {
        this.source.output()
                .send(MessageBuilder.withPayload("消息体").build());
        return "success";
    }
}
